package cn.meeh.sscircle.common.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Zachary on 15/7/27.
 */
public class NetworkUtils {

    public static final int NONE = 0;
    public static final int WIFI = 1;
    public static final int MOBILE = 2;


    public static boolean isNetworkAvailable(Context context) {
        boolean netWorkStatus = false;
        if (context != null) {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connManager.getActiveNetworkInfo() != null) {
                netWorkStatus = connManager.getActiveNetworkInfo().isAvailable();
            }
        }

        return netWorkStatus;
    }

    public static int getNetworkState(Context context) {
        if (context != null) {
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connManager != null) {
                NetworkInfo networkInfo = connManager.getNetworkInfo(1);
                NetworkInfo.State state;
                if (networkInfo != null) {
                    state = networkInfo.getState();
                    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                        return 1;
                    }
                }

                networkInfo = connManager.getNetworkInfo(0);
                if (networkInfo != null) {
                    state = networkInfo.getState();
                    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                        return 2;
                    }
                }
            }
        }

        return 0;
    }

    //获取ip地址
    public static  String getLocalIpAddress()
    {
        try
        {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
                {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress())
                    {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }
        catch (SocketException ex)
        {
            Log.d("ip地址", "ip地址获取失败");
        }
        return null;
    }
}
